package com.yuliang.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.yuliang.domain.R;
import com.yuliang.domain.dto.UpdateCategoryDto;
import com.yuliang.domain.entity.Category;
import com.yuliang.domain.vo.CategoryVo;
import com.yuliang.domain.vo.ExcelCategoryVo;
import com.yuliang.enums.AppHttpCodeEnum;
import com.yuliang.service.CategoryService;
import com.yuliang.utils.BeanCopyUtils;
import com.yuliang.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/content/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/listAllCategory")
    public R getListAllCategory(){
        return categoryService.getListAllCategory();
    }

    @GetMapping("/list")
    public R categoryPages(Integer pageNum,Integer pageSize,String name,String status){
        return categoryService.categoryPages(pageNum,pageSize,name,status);
    }

    @PostMapping
    public R addCategory(@RequestBody CategoryVo categoryVo){
        return categoryService.addCategory(categoryVo);
    }

    @GetMapping("{id}")
    public R getCategoryDetail(@PathVariable("id") Long id){
        return categoryService.getCategoryDetail(id);

    }

    @PutMapping
    public R updateCategory(@RequestBody UpdateCategoryDto updateCategoryDto){
        return categoryService.updateCategory(updateCategoryDto);
    }

    @DeleteMapping("{id}")
    public R deleteCategory(@PathVariable("id") List<Long> ids){
        return categoryService.deleteCategory(ids);

    }
    @PreAuthorize("@perms.hasPermission('content:category:export')")
    @GetMapping("/export")
    public void export(HttpServletResponse response){
        try {
            //设置响应头
            WebUtils.setDownLoadHeader("分类.xlsx",response);
            //获取数据
            List<Category> list = categoryService.list();
            List<ExcelCategoryVo> easyExcels = BeanCopyUtils.copyBeanList(list, ExcelCategoryVo.class);
            //写入excel
            EasyExcel.write(response.getOutputStream(), ExcelCategoryVo.class).autoCloseStream(Boolean.FALSE).sheet("分类导出")
                    .doWrite(easyExcels);
        } catch (Exception e) {
            //如果出现异常也要响应json
            R result = R.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
            WebUtils.renderString(response, JSON.toJSONString(result));
        }
    }
}
